<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联租金表ID（对应租金记录）" prop="rentId">
        <el-input v-model="queryParams.rentId" placeholder="请输入关联租金表ID（对应租金记录）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="调整前租金金额（单位：元）" prop="oldRent">
        <el-input v-model="queryParams.oldRent" placeholder="请输入调整前租金金额（单位：元）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="调整后租金金额（单位：元）" prop="newRent">
        <el-input v-model="queryParams.newRent" placeholder="请输入调整后租金金额（单位：元）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="申请人ID（关联用户表）" prop="applicantId">
        <el-input v-model="queryParams.applicantId" placeholder="请输入申请人ID（关联用户表）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="审批人ID（关联用户表，审批完成前为空）" prop="approverId">
        <el-input v-model="queryParams.approverId" placeholder="请输入审批人ID（关联用户表，审批完成前为空）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="租金调整原因说明（500字以内）" prop="applyReason">
        <el-input v-model="queryParams.applyReason" placeholder="请输入租金调整原因说明（500字以内）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="审批状态（PENDING-待审批/APPROVED-已通过/REJECTED-已拒绝）" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审批状态（PENDING-待审批/APPROVED-已通过/REJECTED-已拒绝）" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="驳回原因说明（仅驳回时需填写）" prop="rejectReason">
        <el-input v-model="queryParams.rejectReason" placeholder="请输入驳回原因说明（仅驳回时需填写）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="申请提交时间" prop="applyTime">
        <el-date-picker v-model="queryParams.applyTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item label="审批操作时间（通过/驳回时更新）" prop="auditTime">
        <el-date-picker v-model="queryParams.auditTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                  >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   >导出</el-button>
      </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

            <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="审批流程唯一标识" align="center" prop="auditId" />
      <el-table-column label="关联租金表ID（对应租金记录）" align="center" prop="id" />
      <el-table-column label="房屋ID" align="center" prop="houseId" />
      <el-table-column label="调整前租金金额（单位：元）" align="center" prop="oldRent" />
      <el-table-column label="调整后租金金额（单位：元）" align="center" prop="newRent" />
      <el-table-column label="申请人ID（关联用户表）" align="center" prop="applicantId" />
      <el-table-column label="审批人ID（关联用户表，审批完成前为空）" align="center" prop="approverId" />
      <el-table-column label="租金调整原因说明（500字以内）" align="center" prop="applyReason" />
      <el-table-column label="审批状态（PENDING-待审批/APPROVED-已通过/REJECTED-已拒绝）" align="center" prop="auditStatus" />
      <el-table-column label="驳回原因说明（仅驳回时需填写）" align="center" prop="rejectReason" />
      <el-table-column label="申请提交时间" align="center" prop="applyTime" width="180">
        <template v-slot="scope">
          <span>{{ scope.row.applyTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批操作时间（通过/驳回时更新）" align="center" prop="auditTime" width="180">
        <template v-slot="scope">
          <span>{{ scope.row.auditTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
  <template v-slot="scope">
    <div class="action-group">
      <template v-if="scope.row.auditStatus === 'PENDING'">
        <el-button 
          size="mini"
          type="success" 
          icon="el-icon-check"
          class="action-btn"
          @click="handleApprove(scope.row, 'APPROVED')"
        >
          <span class="btn-text">通过</span>
        </el-button>
        <el-button 
          size="mini"
          type="danger"
          icon="el-icon-close"
          class="action-btn"
          @click="handleApprove(scope.row, 'REJECTED')"
        >
          <span class="btn-text">驳回</span>
        </el-button>
      </template>
      <el-tag 
        v-else 
        :type="scope.row.auditStatus === 'APPROVED' ? 'success' : 'danger'"
        class="status-tag"
      >
        {{ scope.row.auditStatus === 'APPROVED' ? '已审批' : '已驳回' }}
      </el-tag>
    </div>
  </template>
</el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <ShenPi ref="formRef" @success="getList" />
    </div>
</template>

<script>
import * as ShenPiApi from '@/api/system/shenpi/shenpi';
import ShenPi from './ShenPi.vue';

export default {
  name: "shenpi",
  components: {
         ShenPi,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
              // 总条数
        total: 0,
      // 租金调整审批流程记录表（记录租金调整申请和审批流程）列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
                    pageNo: 1,
            pageSize: 10,
        rentId: null,
        oldRent: null,
        newRent: null,
        applicantId: null,
        approverId: null,
        applyReason: null,
        auditStatus: null,
        rejectReason: null,
        applyTime: [],
        auditTime: [],
        createTime: [],
      },
            };
  },
  created() {
    this.getList();
  },
  methods: {
// 添加状态格式化方法
  formatStatus(status) {
    const map = {
      PENDING: '待审批',
      APPROVED: '已通过',
      REJECTED: '已驳回'
    };
    return map[status] || '未知状态';
  },
  getStatusType(status) {
    const typeMap = {
      PENDING: 'warning',
      APPROVED: 'success',
      REJECTED: 'danger'
    };
    return typeMap[status] || 'info';
  },
    /** 查询列表 */
    async getList() {
  try {
    this.loading = true;
    const res = await ShenPiApi.getshenpi(this.queryParams);
    this.list = res.data.list;
    this.total = res.data.total;
    console.log(this.list);
  } finally {
    this.loading = false;
  }
},
    /** 搜索按钮操作 */
   handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const auditId = row.auditId;
      await this.$modal.confirm('是否确认删除租金调整审批流程记录表（记录租金调整申请和审批流程）编号为"' + auditId + '"的数据项?')
      try {
       await RentAdjustAuditApi.deleteRentAdjustAudit(auditId);
       await this.getList();
       this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有租金调整审批流程记录表（记录租金调整申请和审批流程）数据项?');
      try {
        this.exportLoading = true;
        const data = await RentAdjustAuditApi.exportRentAdjustAuditExcel(this.queryParams);
        this.$download.excel(data, '租金调整审批流程记录表（记录租金调整申请和审批流程）.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    // 审批操作
    async handleApprove(row, status) {
  try {
    const isApprove = status === 'APPROVED';
    const params = {
      auditId: row.auditId,
      // houseId: row.houseId, // 确保 row 对象中有 houseId 字段
      isApproved: isApprove,
      rejectReason: isApprove ? null : '' 
    };

    if (!isApprove) {
      const { value } = await this.$prompt('请输入驳回原因（3-200字）', '驳回确认', {
        inputPattern: /^[\s\S]{3,200}$/,
        inputErrorMessage: '驳回原因需填写3-200个字符'
      });
      params.rejectReason = value;
    } else {
      await this.$modal.confirm('确定通过该申请吗？', '通过确认');
    }
  console.log('最终请求参数:', params); // 调试日志
    await ShenPiApi.handleApproveApi(params);
    this.$modal.msgSuccess(`${isApprove ? '通过' : '驳回'}操作成功`);
    await this.getList();
  } catch (error) {
    if (error !== 'cancel') {
      const action = status === 'APPROVED' ? '通过' : '驳回';
      // this.$modal.msgError(`${action}操作失败：${error.message || error}`);
    }
  }
}
              }

};
</script>
